package com.hongdee.crm.remindClose.service.impl;

import com.hongdee.common.util.StringUtil;
import com.hongdee.common.util.TokenUtil;
import com.hongdee.crm.Constant;
import com.hongdee.crm.carConfig.dao.ITCrmCarRefDao;
import com.hongdee.crm.carConfig.service.ITcrmCarConfService;
import com.hongdee.crm.remindClose.dao.ITCrmCarRemindCloseDao;
import com.hongdee.crm.remindClose.entity.TCrmCarRemindClose;
import com.hongdee.crm.remindClose.service.ITCrmCarRemindCloseService;
import jdk.nashorn.internal.parser.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.*;

/**
 * 名  称:TCrmCarRemindCloseServiceImpl
 * 类  型:class
 * 描  述:
 * 路  径:com.hongdee.crm.remindClose.service.impl
 * 作  者: 术洪超
 * 日  期:2017-03-21 09:42
 */
@Service
public class TCrmCarRemindCloseServiceImpl implements ITCrmCarRemindCloseService {

    @Autowired
    private ITCrmCarRemindCloseDao itCrmCarRemindCloseDao;

    @Autowired
    private ITCrmCarRefDao carRefDao;

    @Autowired
    private ITcrmCarConfService confService;

    /**
     * @param uid      登录用户 ID
     * @param start    起始记录
     * @param limit    页面大小
     * @param plateNum 车牌号
     * @param vin      车架号
     * @return Map
     * @throws Exception
     * @desc 通过 JDBCDao分页查询
     * @author 术洪超
     */
    @Override
    public Map closePage(String start, String limit, String uid, String plateNum, String vin, String carId, String pcode, String code) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append("select distinct temp.* from (");
        sql.append("select remind.id,remind.vin,remind.company_id,remind.owner_name,remind.plate_num,remind.type_code, " +
                "remind.type_pcode,");
        if (!StringUtils.isEmpty(carId)) {
            sql.append("def.`name` defName,");
        } else {
            sql.append("GROUP_CONCAT(def.`name`) defName,");
        }

        sql.append("remind.user_carid as carId from t_crm_car_remindclose remind " +
                "left JOIN " +
                "t_bc_param_def def " +
                "ON " +
                "remind.type_code=def.`code` ");
        List params = new ArrayList();
        sql.append(" where  remind.company_id = ? ");
        params.add(TokenUtil.getCompanyId(uid));
        if (!StringUtils.isEmpty(plateNum)) {
            sql.append(" and remind.plate_num like ? ");
            params.add("%" + plateNum + "%");
        }
        if (!StringUtils.isEmpty(vin)) {
            sql.append(" and remind.vin like ? ");
            params.add("%" + vin + "%");
        }
        if (!StringUtils.isEmpty(pcode)) {
            sql.append(" and type_pcode=? ");
            params.add(pcode);
        }
        if (!StringUtils.isEmpty(code)) {
            sql.append(" and type_code=? ");
            params.add(code);
        }

        if (!StringUtils.isEmpty(carId)) {
            sql.append(" and  remind.user_carid=? ");
            params.add(carId);
        } else {
            sql.append(" group by remind.user_carid ");
        }

        sql.append(" ) temp");


        return this.itCrmCarRemindCloseDao.page(sql.toString(), params.toArray(), start, limit);
    }

    /**
     * @param uid      登录用户 ID
     * @param start    起始记录
     * @param limit    页面大小
     * @param plateNum 车牌号
     * @param vin      车架号
     * @return Map
     * @throws Exception
     * @desc 通过 JDBCDao分页查询
     * @author 术洪超
     */
    @Override
    public Map carPage(String start, String limit, String uid, String plateNum, String vin, String typePcode, String typeCode) throws Exception {
        StringBuffer sql = new StringBuffer();
        String companyId = TokenUtil.getCompanyId(uid);
        List params = new ArrayList();
        sql.append("select c.id userCarid,c.vin,c.plate_num,c.owner_name,c.owner_phone,c.last_maintain_date from T_CRM_CAR c " +
                "where  not EXISTS  (select rc.user_carid from t_crm_car_remindclose rc where c.vin=rc.vin and rc.company_id=? ");
        params.add(companyId);
        List<String> typeCodes = new ArrayList<>();
        if ("".equals(typeCode) && !"".equals(typePcode)) {
            this.buildParamsChild(typePcode, typeCodes);
        } else if (!"".equals(typeCode)) {
            typeCodes.add(typeCode);
        }
        if (typeCodes.size() > 0) {
            sql.append(" and rc.type_code in(");
            for (int i = 0; i < typeCodes.size(); i++) {
                sql.append(" ?");
                params.add(typeCodes.get(i));
                if (i < (typeCodes.size() - 1)) {
                    sql.append(",");
                }
            }
            sql.append(" ) ");

        }

        sql.append(" ) ");


        sql.append(" and c.company_id = ?");
        params.add(companyId);

        if (!StringUtils.isEmpty(plateNum)) {
            sql.append(" and c.plate_num like ?");
            params.add("%" + plateNum + "%");
        }
        if (!StringUtils.isEmpty(vin)) {
            sql.append(" and c.vin like ?");
            params.add("%" + vin + "%");
        }

//        Constant.VIN_TO_SQL(sql,uid,"c");
        confService.crmCarConfToSql(uid, sql, "c",companyId);
//        // 车辆分配
//        // 查询其分配的车辆
//        Map info = refCar(uid);
//        //未分配车辆
//        if (null == info || info.size() == 0) {
//            throw new Exception("该用户未分配车辆，请联系管理员！");
//        }
//
//        //车辆分配类型
//        String refType = String.valueOf(info.get("type"));
//        if (StringUtils.isEmpty(refType) || "null".equals(refType.toLowerCase())) {
//            throw new Exception("该用户未分配车辆，请联系管理员！");
//        }
//        //车辆分配值，车属号 或车尾数，vin时 另行处理
//        String refValue = String.valueOf(info.get("value"));
//        refValue = refValue.replaceAll(",", "");
//        //根据类型取车辆
//
//        switch (refType) {
//            case Constant.CAR_WH:
//                sql.append(" AND  c.plate_num REGEXP ? ");
//                params.add("[" + refValue + "]$");
//                break;
//            case Constant.CAR_WS:
//                //先不写
//                sql.append( " AND c.plate_num REGEXP ? ");
//                params.add(".*[" + refValue + "][A-Za-z]*$");
//                //根据尾数查询
//                break;
//            case Constant.CAR_ALL:
//                //全部车辆
//                break;
//            default:
//                throw new Exception("车辆分配错误，请联系管理员！");
//        }


        return this.itCrmCarRemindCloseDao.page(sql.toString(), params.toArray(), start, limit);
    }

    /**
     * @param uid  登录用户 ID
     * @param data 要保存的关闭提醒实体
     * @return ResultEntity
     * @throws Exception
     * @desc
     * @author 术洪超
     */
    @Override
    public TCrmCarRemindClose save(TCrmCarRemindClose data, String uid) throws Exception {

        data.setId(null);
        data.setCreateUser(uid);
        data.setCompanyId(TokenUtil.getCompanyId(uid));
        data.setCreateTime(Calendar.getInstance().getTimeInMillis());

//        System.out.println(data.getUserCarid());

        this.itCrmCarRemindCloseDao.saveOrUpdate(data);
        return data;
    }


    /**
     * @param uid 登录用户 ID
     * @param id  要删除的提醒实体主键
     * @return ResultEntity
     * @throws Exception
     * @desc ResultEntity
     * @author 术洪超
     */
    @Override
    public void del(String id, String uid, String carId) throws Exception {

        String sql = "delete from T_CRM_CAR_REMINDCLOSE where 1=1";
        List params = new ArrayList();
        if (StringUtils.isEmpty(id) && StringUtils.isEmpty(carId)) {
            throw new Exception("请选择要开启提醒的车辆!");
        }
        if (!StringUtils.isEmpty(id)) {
            sql += " and id = ?";
            params.add(id);
        }
        if (!StringUtils.isEmpty(carId)) {
            sql += " and user_carid = ?";
            params.add(carId);
        }
        sql += "  and company_id = ?";
        params.add(TokenUtil.getCompanyId(uid));
        this.itCrmCarRemindCloseDao.executeSQL(sql, params.toArray());

    }

    private Map<String, Object> refCar(String uid) throws Exception {
        String sql = "select  * from t_crm_car_ref where u_id = ? and status = '1' ";
        Map info = this.itCrmCarRemindCloseDao.info(sql, uid);
        return info;
    }

    /**
     * @param pcode
     * @param code
     * @param uid
     * @param remindCloses
     * @throws Exception
     */
    @Override
    public void saveRemindCloseByTaskType(String pcode, String code, String uid, List<TCrmCarRemindClose> remindCloses) throws Exception {
        for (TCrmCarRemindClose remindClose : remindCloses) {
            List<String> typeCodes = new ArrayList<>();
            if ("".equals(pcode)) {
                List<Map<String, Object>> typePcodes = this.getTypePcodes();
                for (Map map : typePcodes) {
                    typeCodes = new ArrayList<>();
                    String c = String.valueOf(map.get("code"));
                    this.buildParamsChild(c, typeCodes);
                    this.itCrmCarRemindCloseDao.executeSQL("delete from T_CRM_CAR_REMINDCLOSE where user_carid=? and type_pcode=?", remindClose.getUserCarid(), pcode);
                    this.saveRemindClose(c, typeCodes, uid, remindClose);
                }
            } else {
                if (!"".equals(pcode) && "".equals(code)) {
                    this.buildParamsChild(pcode, typeCodes);
                    this.itCrmCarRemindCloseDao.executeSQL("delete from T_CRM_CAR_REMINDCLOSE where user_carid=? and type_pcode=?", remindClose.getUserCarid(), pcode);
                    this.saveRemindClose(pcode, typeCodes, uid, remindClose);
                } else if (!"".equals(pcode) && !"".equals(code)) {
                    typeCodes.add(code);
                    this.itCrmCarRemindCloseDao.executeSQL("delete from T_CRM_CAR_REMINDCLOSE where user_carid=? and type_pcode=? and type_code=?",
                            remindClose.getUserCarid(), pcode, code);
                    this.saveRemindClose(pcode, typeCodes, uid, remindClose);
                }
            }
        }

    }

    private List<Map<String, Object>> getTypePcodes() throws Exception {
        String sql = "select * from t_bc_param_def where p_code=?";
        return this.itCrmCarRemindCloseDao.list(sql, "task");
    }

    /**
     * 生成保存关闭提醒实体
     *
     * @param pcode
     * @param typeCodes
     * @param uid
     * @param tCrmCarRemindClose
     * @throws Exception
     */
    private void saveRemindClose(String pcode, List<String> typeCodes, String uid, TCrmCarRemindClose tCrmCarRemindClose) throws Exception {
        String companyId = TokenUtil.getCompanyId(uid);
        List<TCrmCarRemindClose> tCrmCarRemindCloses = new ArrayList<>();
        for (String code : typeCodes) {
            TCrmCarRemindClose remindClose = new TCrmCarRemindClose();
            remindClose.setCompanyId(companyId);
            remindClose.setTypeCode(code);
            remindClose.setTypePcode(pcode);
            remindClose.setUserCarid(tCrmCarRemindClose.getUserCarid());
            remindClose.setOwnerName(tCrmCarRemindClose.getOwnerName());
            remindClose.setPlateNum(tCrmCarRemindClose.getPlateNum());
            remindClose.setVin(tCrmCarRemindClose.getVin());
            remindClose.setCreateTime(new Date().getTime());
            remindClose.setCreateUser(uid);
            tCrmCarRemindCloses.add(remindClose);
        }
        this.itCrmCarRemindCloseDao.saveOrUpdateList(tCrmCarRemindCloses);
    }


    public List<Map<String, Object>> buildParamsChild(String code, List<String> typeCodes) throws Exception {

        String sqlStr = "select def.* from t_bc_param_def def where def.p_code=? ";
        List<Map<String, Object>> child = this.itCrmCarRemindCloseDao.list(sqlStr, code);
        return buildDeptParent(child, typeCodes);
    }

    public List<Map<String, Object>> buildDeptParent(List<Map<String, Object>> paranet, List<String> typeCodes) throws Exception {
        if (paranet.size() == 0) {
            return paranet;
        }
        String code;
        for (Map<String, Object> temp : paranet) {
            code = String.valueOf(temp.get("code"));
            String type = String.valueOf(temp.get("type"));
            List<Map<String, Object>> childList = buildParamsChild(code, typeCodes);
            temp.put("child", childList);
            if (type.equals("1")) {
                String pcode = String.valueOf(temp.get("pCode"));
                if (!typeCodes.contains(pcode)) {
                    typeCodes.add(pcode);
                }
            }
        }
        return paranet;
    }

}
